<template>
  <div class="login_container">
    <div class="taitou_title">
      <div class="login_logo">
        <img src="@/assets/images/duck.png" alt="">
      </div>
      <h1 class="login_title">博客鸭</h1>
    </div>
    <div class="login_tab_wrapper height_light_bgcolor">
      <div style="display: flex;justify-content: flex-end;padding-right: 20px;">
        <el-button type="primary" link @click="$router.push('/')">&lt; 返回首页</el-button>
      </div>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="登录" name="first">
          <div class="login_tab_content">
            <el-form label-position="top" label-width="100px" style="width:70%;margin: 0 auto;" ref="loginRuleFormRef"
              :rules="loginRules" :model="formLabelAlign" status-icon>
              <el-form-item label="用户名" prop="username">
                <el-input v-model="formLabelAlign.username" autocomplete="off" />
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="formLabelAlign.password" autocomplete="off" type="password" />
              </el-form-item>
              <el-form-item label="验证码" prop="cpyto">
                <el-row justify="space-between" align="middle" :gutter="20">
                  <el-col :span="14">
                    <el-input v-model="formLabelAlign.cpyto" autocomplete="off" />
                  </el-col>
                  <el-col :span="10" style="display:flex;align-items: center;">
                    <img :src="identifyCode" alt="" style="width:100%;height:32px" class="cursor_class"
                      @click="getCytptoCode">
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" style="width:100%;margin-top: 20px;"
                  @click="loginSubmitForm(loginRuleFormRef)" :loading="loginBtnLoading">登录</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane label="注册" name="second">
          <el-form label-position="top" label-width="100px" style="width:70%;margin: 0 auto;" ref="regRuleFormRef"
            :rules="regRules" :model="regFormLabelAlign" status-icon>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="regFormLabelAlign.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="regFormLabelAlign.password" autocomplete="off" type="password" />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmpwd">
              <el-input v-model="regFormLabelAlign.confirmpwd" autocomplete="off" type="password" />
            </el-form-item>
            <el-form-item label="验证码" prop="cpyto">
              <el-row justify="space-between" align="middle" :gutter="20">
                <el-col :span="14">
                  <el-input v-model="regFormLabelAlign.cpyto" autocomplete="off" />
                </el-col>
                <el-col :span="10" style="display:flex;align-items: center;">
                  <img :src="identifyCode" alt="" style="width:100%;height:32px" class="cursor_class"
                    @click="getCytptoCode">
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="width:100%;margin-top: 20px;" :loading="regBtnLoading"
                @click="regSubmitForm(regRuleFormRef)">
                注册</el-button>
            </el-form-item>
          </el-form>
          <div style="display: flex;justify-content: flex-end;padding-right: 20px;">
            <el-button type="primary" link @click="handleClickToLogin">已有账号？去登陆</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <Footer />
  </div>
</template>

<script lang="ts" setup>
import Footer from '@/components/Footer/index.vue'
import Identify from '@/components/Identify/index.vue';
import { onMounted, ref, watch, reactive, getCurrentInstance } from 'vue'
import router from '@/router/index'
import { useRoute } from 'vue-router';
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  Search,
  Plus,
  Edit
} from '@element-plus/icons-vue'
import type { TabsPaneContext } from 'element-plus'
import { getCaptchaImage, login, register } from '@/api/login'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import store from '@/store';
interface Login {
  username: string,
  password: string,
  code: string,
  uuid: string
}
const { proxy } = getCurrentInstance()
const loginRuleFormRef = ref<FormInstance>()
const regRuleFormRef = ref<FormInstance>()
const route = useRoute()
const activeName = ref('first')
// 验证码
const identifyCode = ref('') // 默认值
// uuid
const uuidString = ref('')
// 登录按钮loading
const loginBtnLoading = ref(false)
const regBtnLoading = ref(false)
const formLabelAlign = reactive({
  username: '',
  password: '',
  cpyto: '',
})
const regFormLabelAlign = reactive({
  username: '',
  password: '',
  confirmpwd: '',
  cpyto: '',
})
const loginRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'change',
    },
  ],
  cpyto: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'change',
    }
  ]
})
const regRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'change',
    },
  ],
  confirmpwd: [
    {
      required: true,
      message: '请输入确认密码',
      trigger: 'change',
    },
  ],
  cpyto: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'change',
    }
  ]
})
// 清空表单值
const clearAllFormValue = () => {
  formLabelAlign.username = ''
  formLabelAlign.password = ''
  formLabelAlign.cpyto = ''
  regFormLabelAlign.username = ''
  regFormLabelAlign.password = ''
  regFormLabelAlign.confirmpwd = ''
  regFormLabelAlign.cpyto = ''
}
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
  getCytptoCode()
  clearAllFormValue()
}
if (route.query.activeName) {
  activeName.value = route.query.activeName as string
}
/**
 * 获取验证码
 */
const getCytptoCode = async () => {
  const res: any = await getCaptchaImage()
  identifyCode.value = 'data:image/gif;base64,' + res.img
  uuidString.value = res.uuid
  // console.log('页面一开始加载的uuid-------------------------------------------------', uuidString.value);
}
// 登录
const loginSubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    // console.log('登录验证码uuid---------------------------', uuidString.value);
    if (valid) {
      try {
        let loginObj: Login = {
          username: formLabelAlign.username,
          password: formLabelAlign.password,
          code: formLabelAlign.cpyto,
          uuid: uuidString.value,
        }
        loginBtnLoading.value = true
        const res: any = await login(loginObj)
        if (res) {
          ElMessage({
            message: '登录成功',
            type: 'success',
            duration: 5 * 1000
          })
          localStorage.setItem('token', res.token)
          store.commit('updateLoginState',true)
          router.push('/')
        }
      } catch (res: any) {
        // 处理不是200的请求
        if (res.msg === '验证码已失效') {
          getCytptoCode()
          formLabelAlign.cpyto = ''
        }
        if (res.msg === '用户不存在/密码错误') {
          // formLabelAlign.username = ''
          formLabelAlign.password = ''
          formLabelAlign.cpyto = ''
        }
        if (res.msg === '验证码错误') {
          getCytptoCode()
          formLabelAlign.cpyto = ''
        }
        
      } finally {
        loginBtnLoading.value = false
      }
    } else {
    }
  })
}
const regSubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (regFormLabelAlign.password !== regFormLabelAlign.confirmpwd) {
    return ElMessage({
      message: '两次密码输入不一致！',
      type: 'error',
      duration: 5 * 1000
    })
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        regBtnLoading.value = true
        let regObj: Login = {
          username: regFormLabelAlign.username,
          password: regFormLabelAlign.password,
          code: regFormLabelAlign.cpyto,
          uuid: uuidString.value,
        }
        const res: any = await register(regObj)
        if (res) {
          ElMessage({
            message: '注册成功',
            type: 'success',
            duration: 5 * 1000
          })
          handleClickToLogin()
        }
      } catch (err: any) {
        // 处理不是200的请求
        if (err.msg === '验证码已失效') {
          getCytptoCode()
          formLabelAlign.cpyto = ''
        }
        if (err.msg === '验证码错误') {
          getCytptoCode()
          formLabelAlign.cpyto = ''
        }
      } finally {
        regBtnLoading.value = false
      }
    } else {
    }
  })
}
const handleClickToLogin = () => {
  router.push('/login');
  activeName.value = 'first'
}
onMounted(() => {
  getCytptoCode()
})

</script>

<style scoped lang="scss">
// @import '@/assets/style/reset.scss';
@import './index.scss';
</style>
